const express = require("express");
const app = express();
const port = 9527;
const { system_user } = require("./model");
// console.log(student)
app.use(express.json()); // for parsing application/json
// 获取一个用户
app.get("/system/user/:id", (req, res) => {
  console.log(222, req.params)
  system_user
    .findOne({
      where: { id: req.params.id },
    })
    .then((result) => {
      res.send({ code: 200, data: result, msg: "查询成功" });
    });
});
// 新增一个学生
app.post("/system/user", (req, res) => {
  console.log(req.body);
  const result = system_user.create({ ...req.body });
  res.send({ code: 200, data: result, msg: "新增成功" });
});
// 更新
app.put("/system/user", (req, res) => {
  console.log(3333, req.body);

  system_user.update({ ...req.body }, {
    where: {
      id: req.body.id
    }
  }).then(() => {
    res.send({ code: 200, data: null, msg: "修改成功" });
  });

});
// 删除
app.delete("/system/user/:id", (req, res) => {
  system_user.destroy({
    where: {
      id: req.params.id
    }
  }).then(() => {
    res.send({ code: 200, data: null, msg: "删除成功" });
  })

});
// 分页查询学生
app.post("/system/user/page", (req, res) => {
  console.log(1111, req.body)
  const offset = req.body.pageNum - 1
  const limit = req.body.pageSize
  const result = system_user.findAndCountAll({
    // where: {},
    offset: +offset,
    limit: +limit
  }).then(result => {
    res.send({ code: 200, data: { total: result.count, rows: result.rows }, msg: "查询成功" });
  }).catch(() => {
    res.send({ code: 500, data: null, msg: "查询失败" });
  })


});
app.post('/system/user/login', (req, res) => {
  if (!req.body.loginId) {
    res.send({ success: false, msg: '请输入账号', data: null })
  }
  if (!req.body.password) {
    res.send({ success: false, msg: '请输入密码', data: null })
  }
  system_user.findOne({
    where: { loginId: req.body.loginId, password: req.body.password }
  }).then(result => {
    if (result && result.password === req.body.password) {
      res.cookie('token', result.uuid||'', {
        path: '/',
        domain: 'localhost',
        maxAge:  3600*60*60*10
        // signed:true// cookie加密
      })

      // req.session.loginUser = result
      console.log(1111, result.uuid)
      res.header('authorization', result.uuid)
      res.send({ success: true, msg: '登录成功', data: result.toJSON() })
    } else {
      res.send({ success: false, msg: '用户不存在或密码错误', data: null })
    }
  })

})
app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});
